<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <backView />
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">编辑{{ PageItem.title }}</text>
    <FormView v-if="form" :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { demographicFields as fieldConfig } from "./fields";
import FormView from "@/components/FormView.vue";
import { request } from "@/service/request";
import { localStg } from "@/utils";
import { PageItem } from "./fields";
import backView from "@/components/backView.vue";

const form = ref<any>();

onMounted(async () => {
  const params: any = Taro.getCurrentInstance().router?.params;
  //  const obj = localStg.get("demographicInfo")
  if (params?.idcard) {
    const result = await request.get<any>(
      `/health_records/HealthRecord/healthRecordInfo/list`,
      {
        idNumber: params.idcard,
      },
      {
        useErrMsg: true,
      }
    );

    console.log("result===", result);
    form.value = result.success.records[0]
    if(!form.value){
      Taro.showModal({
        title: "提示",
        content: "未认证用户无法查看人口学信息",
        confirmText: "确定",
        cancelText: "取消",
      }).then(() => { 
        setTimeout(() => {
          Taro.navigateBack();
        }, 300);
      });
      return;
    }
    return;
  }
  if (params?.id) {
    await loadRecordData(params.id);
  }
});

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(
      `${PageItem.commUrl}/queryById?id=${id}`,
      {},
      {
        useErrMsg: true,
      }
    );

    console.log("result", result);

    if (result.success) {
      form.value = result.success;
    }
    console.log("form", form);
  } catch (error) {
    console.error("加载记录失败:", error);
    Taro.showToast({ title: "加载记录失败", icon: "error" });
  }
}

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    // if (!form.serverName) {
    //   Taro.showToast({ title: "请输入下单人姓名", icon: "error" });
    //   return;
    // }
    // if (!form.serverIdnumber) {
    //   Taro.showToast({ title: "请输入下单人证件号码", icon: "error" });
    //   return;
    // }
    // if (!form.serverTel) {
    //   Taro.showToast({ title: "请输入下单人手机号码", icon: "error" });
    //   return;
    // }

    // 提交数据
    const params = {
      ...form,
    };

    const result = await request.put<any>(`${PageItem.commUrl}/edit`, params, {
      useErrMsg: true,
    });

    if (result) {
      Taro.showToast({ title: "更新成功", icon: "success" });

      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    }
  } catch (error) {
    console.error("更新失败:", error);
    Taro.showToast({ title: "更新失败", icon: "error" });
  }
}
</script>
